import os

import wx

from gui.mainwindow import MainWindow
from gui.gui_utils import _pydate2wxdate, _wxdate2pydate
from logic.mainlogic import MainLogic
from logic.global_objs import g
from logic.config import TaskMgr
from datetime import datetime
import wx.propgrid as wxpg
from gui.task_dialog_logic import TaskDialogLogic
from logic.config import Task,Config

class MainWindowLogic:

    def tree_menu(self):
        pass
        #self.win.m_tree_strategies.Bind(wx.EVT_TREE_ITEM_MENU,self.on_tree_menu,self.win.m_menuitem_del)
        #self.win.m_menuitem_del.

    def load_tasks(self):
        self.win.m_tree_strategies.DeleteAllItems()
        # 策略树
        self.images = wx.ImageList(16, 16, True)
        self.images.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, (16, 16)))
        self.images.Add(wx.ArtProvider.GetBitmap(wx.ART_HELP_FOLDER, wx.ART_OTHER, (16, 16)))
        self.images.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, (16, 16)))

        self.win.m_tree_strategies.SetImageList(self.images)
        root = self.win.m_tree_strategies.AddRoot('策略', image=0)

        from logic.config import TaskMgr
        task_tree = TaskMgr().task_tree()
        for cat, tasks in task_tree.items():
            cat = self.win.m_tree_strategies.AppendItem(root, cat, image=1)
            for t in tasks:
                self.win.m_tree_strategies.AppendItem(cat, text=t.name, image=2,data=t)
        self.win.m_tree_strategies.ExpandAll()
        self.win.m_tree_strategies.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.tree_click_item)

    def on_tree_menu(self,event):
        print(event)

    def handle_data(self, **data):
        type = data['event_type']
        if type == g.BKT_START:
            self.win.m_button_bkt.Enable(False)
        elif type == g.BKT_FINISHED:
            self.win.m_button_bkt.Enable(True)
            self.win.m_text_msg.WriteText('\n任务回测完成！')
            results = TaskMgr().get_results_list()

            self.m_pg_results.InsertChoice(label=data['name'],index=0,value=1)
            self.m_pg_results.SetValue([data['name']])
            self.on_btn_analysis(None)

            #self.m_pg_results.SetValue(results)

        elif type == g.TASK_CHANGED:
            self.load_tasks()
        elif type == g.BKT_PROGRESS:
            self.win.m_gauge.SetValue(data['rate']*100)
        elif type == g.MESSAGE:
            self.win.m_text_msg.WriteText(data['message'])
        elif type == g.GRAPH_RESULT:
            self.show_results(data)

    def show_results(self,data):
        from gui.graph.plotly_mgr import PlotlyMgr
        mgr = PlotlyMgr()

        mgr.add_lines(data['equity'],1,1)
        mgr.add_table(data['ratio'],1,2)
        mgr.add_bar(data['yearly'].T, 2, 2)
        mgr.add_heatmap(data['corr'],2,1)

        filename = Config.get_config_path() + '/bkt_result.html'
        mgr.show(filename=filename)
        self.web_panel.show_file(filename)
        #from gui.gui_utils import show_df
        #try:
        #    show_df(self.win.m_grid_ratio, data['ratio'])
        #except:
        #    pass
        #self.plot.show_data(data)

    def __init_pg(self):
        pg = self.win.m_pg_analysis
        pg.Append(wxpg.PropertyCategory("1 - 基础属性"))

        self.m_pg_date_start = wxpg.DateProperty("起始日期")
        # 初始化起始日期为2010-01-01
        start_date = wx.DateTimeFromDMY(1, 0, 2010)
        self.m_pg_date_start.SetValue(start_date)
        pg.Append(self.m_pg_date_start)

        self.m_pg_date_end = wxpg.DateProperty('结束日期')
        self.m_pg_date_end.SetValue(datetime.now())
        pg.Append(self.m_pg_date_end)

        # 基准池
        codes = Config.get_index_codes()
        self.m_pg_codes = wxpg.MultiChoiceProperty('选择基准', choices=codes, value=codes[0:1])
        pg.Append(self.m_pg_codes)

        # 策略结果
        results = TaskMgr().get_results_list()
        self.m_pg_results = wxpg.MultiChoiceProperty('策略列表', choices=results, value=results[0:2])

        pg.Append(self.m_pg_results)


    def OnEraseBack(self, event):
        self.win.m_splitter.SetSashPosition(230)

    def __init__(self):

        self.win = MainWindow(None)
        self.logic = MainLogic(self)
        self.win.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBack)

        self.win.m_button_add.Bind(wx.EVT_BUTTON, self.on_btn_add)
        self.win.m_button_del.Bind(wx.EVT_BUTTON, self.on_btn_del)
        self.win.m_button_bkt.Bind(wx.EVT_BUTTON, self.on_btn_backtest)
        self.win.m_button_results.Bind(wx.EVT_BUTTON, self.on_btn_analysis)

        self.load_tasks()
        g.add_observer(self)

        self.__init_pg()

        #self.tree_menu()

        g.notify(g.TASK_CHANGED,{})


        #结果Tabs

        from gui.widgets import HtmlPanel
        #self.plot = MatplotlibPanel(self.win.m_tabs_results)
        #self.win.m_swin.GetContainingSizer.Add(self.plot)
        #self.win.m_tabs_results.AddPage(self.plot, 'AI量化结果')
        self.web_panel = HtmlPanel(self.win.m_tabs_results)
        self.win.m_tabs_results.AddPage(self.web_panel,'AI量化结果')
        self.web_panel.show_file(Config.get_config_path()+'/bkt_result.html')

        self.win.m_splitter.SetSashPosition(230)

    def on_btn_add(self, event):
        TaskDialogLogic().show(task=Task())

    def on_btn_analysis(self, event):
        start = self.m_pg_date_start.GetValue()
        start = _wxdate2pydate(start).strftime('%Y%m%d')

        end = self.m_pg_date_end.GetValue()
        end = _wxdate2pydate(end).strftime('%Y%m%d')

        benchmarks = self.m_pg_codes.GetValue()
        tasks = self.m_pg_results.GetValue()

        MainLogic(self).analysis(start, end, benchmarks=benchmarks, task_names=tasks)

    def on_btn_del(self, event):
        selects = self.win.m_tree_strategies.GetSelections()
        print(selects)
        if len(selects) == 0:
            wx.MessageBox('请至少选择一个任务。','提示')
        else:
            for item in selects:
                t = self.win.m_tree_strategies.GetItemData(item)
                if t:
                    dlg = wx.MessageDialog(None, '确定要删除"{}"？'.format(t.name), '提示', wx.YES_NO | wx.ICON_QUESTION)
                    if dlg.ShowModal() == wx.ID_YES:
                        TaskMgr().del_task(t.name)

    def show_info__(self, **kwargs):
        if kwargs['event'] == 'msg':
            self.win.m_text_msg.WriteText(kwargs['msg'])

        if kwargs['event'] == 'update_progress':
            self.win.m_gauge.SetValue(kwargs['rate']*100)
        if kwargs['event'] == 'start':
            self.win.m_button_bkt.Enable(False)

        if kwargs['event'] == 'done':
            self.win.m_button_bkt.Enable(True)

        if kwargs['event'] == 'graph':
            pass

    def tree_click_item(self, event):
        item = event.GetItem()
        tree = self.win.m_tree_strategies
        data = tree.GetItemData(item)
        TaskDialogLogic().show(data)

    def show(self):
        self.win.Show()

    def on_btn_backtest(self, event):
        items = self.win.m_tree_strategies.GetSelections()
        if len(items) == 0:
            wx.MessageBox('请至少选择一个任务。','提示')
            return
        else:
            item = items[-1]
            task = self.win.m_tree_strategies.GetItemData(item)
            if task:
                #wx.MessageBox(task.name)
                self.logic.run(task)








